import axios from 'axios';
import router from '../../router'
import { Loading } from 'element-ui';
import {message} from '../msg/resetMessage';

axios.defaults.timeout = 6000;

//创建只用于文件上传的axios实列
const instance=axios.create({})
instance.defaults.timeout = 6000;
//默认axios的基础配置是测试环境
// let BaseUrl='http://127.0.0.1:7778/hrpms'
// let BaseUrl='hrpms/';
let BaseUrl=process.env.VUE_APP_API_URL;
//如果是正式环境则使用一下连接
if (process.env.NODE_ENV==='production')
{
    BaseUrl = '/'
}

axios.defaults.baseURL =BaseUrl;
instance.defaults.baseURL =BaseUrl;

let loadingCount = 0;
let loading;

const startLoading = () => {
    loading = Loading.service({
        lock: true,
        text: '加载中……',
        background: 'rgba(0, 0, 0, 0.7)'
    });
};

const endLoading = () => {
    loading.close();
};

export const showLoading = () => {
    if (loadingCount === 0) {
        startLoading();
    }
    loadingCount += 1;
};

export const hideLoading = () => {
    if (loadingCount <= 0) {
        return;
    }
    loadingCount -= 1;
    if (loadingCount === 0) {
        endLoading();
    }
};

//http request 拦截器
axios.interceptors.request.use(
  config => {
    // const token = getCookie('名称');注意使用的时候需要引入cookie方法，推荐js-cookie
    // const token = localStorage.token;
    // config.data = JSON.stringify(config.data);
    config.headers = {
        'Access-Control-Allow-Credentials':'true',
        'Access-Control-Max-Age': '1800',
        'Access-Control-Allow-Methods':'GET,POST,PUT,POST',
        'Access-Control-Allow-Headers':'x-requested-with,content-type',
        'Content-Type':'application/x-www-form-urlencoded',
        'Access-Control-Allow-Origin':'*',
      // 'Content-Type':'application/json;charset=utf-8'
    };

    // 设置以 form 表单的形式提交参数，如果以 JSON 的形式提交表单，可忽略
    if(config.method  === 'post'){
      // JSON 转换为 FormData
      const formData = new FormData();
      Object.keys(config.data).forEach(key => formData.append(key, config.data[key]))
      config.data = formData
    }

    //请求时将产生的token放到请求头Authorization中
    if (localStorage.token) {   
      // config.headers.Authorization = 'JWT'+localStorage.token;
        config.headers.accessToken = localStorage.token;
    }
      showLoading();
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);


//http response 拦截器
axios.interceptors.response.use(
  response => {
    if(response.data.code =="4101"){
        message({
            showClose: true,
            message: response.data.msg,
            type: 'error',
            duration: 1000
        });

      // Message({
      //   showClose: true,
      //   message: response.data.msg,
      //   type: 'error',
      //   duration: 1000
      // });
      router.push({
        path:"/",
        querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
      })
    }
    hideLoading();
    return response;
  },
  error => {
      hideLoading();
    return Promise.reject(error)
  }
);


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url,params={}){
  return new Promise((resolve,reject) => {
    axios.get(url,{
      params:params
    })
    .then(response => {
      resolve(response.data);
    })
    .catch(err => {
      reject(err)
    })
  })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

 export function post(url,data = {}){
   return new Promise((resolve,reject) => {
     axios.post(url,data)
          .then(response => {
            resolve(response.data);
          },err => {
            reject(err)
          })
   })
 }

/**
 * 导出文件
 * @param url
 * @param data
 * @returns {Promise<unknown>}
 */
export function fpost(url,data = {}){
    return new Promise((resolve,reject) => {
        axios.post(url,data,{responseType: "blob"})
            .then(response => {
                resolve(response.data);
            },err => {
                reject(err)
            })
    })
}

 /**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.patch(url,data)
         .then(response => {
           resolve(response.data);
         },err => {
           reject(err)
         })
  })
}

 /**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.put(url,data)
         .then(response => {
           resolve(response.data);
         },err => {
           reject(err)
         })
  })
}


// instance.defaults.baseURL =this.$BASE_URL;

//http request 拦截器
instance.interceptors.request.use(
    config => {
        config.headers = {
            'Content-Type': 'multipart/form-data',
            // 'Content-Type':'application/x-www-form-urlencoded'
            // 'Content-Type':'application/json;charset=utf-8'
        };


        //请求时将产生的token放到请求头Authorization中
        if (localStorage.token) {
            // config.headers.Authorization = 'JWT'+localStorage.token;
            config.headers.accessToken = localStorage.token;
        }
        showLoading();
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);


//http response 拦截器
instance.interceptors.response.use(
    response => {
        if(response.data.code ==="4101"){
            message({
                showClose: true,
                message: response.data.msg,
                type: 'error',
                duration: 1000
            });
            // message.error({message: response.data.msg});
            router.push({
                path:"/",
                querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
            })
        }
        if(response.data.code ==="fail"){
            message({
                showClose: true,
                message: response.data.msg,
                type: 'error',
                duration: 1000
            });
        }
        hideLoading();
        return response;
    },
    error => {
        hideLoading();
        return Promise.reject(error)
    }
);



/**
 * 封装post请求，用于文件上传
 * @param url
 * @param data
 * @returns {Promise}
 */

export function filepost(url,data = {}){
    return new Promise((resolve,reject) => {
        instance.post(url,data)
            .then(response => {
                resolve(response.data);
            },err => {
                reject(err)
            })
    })
}

/**
 * @Description:获取服务端地址
 * @author      zdc
 * @return
 * @exception
 * @date        2020-04-21 12:10
 */
export function baseurl() {
    return BaseUrl;
}